<!-- 快速跳转页 -->
<template>
    <!-- 单根，全屏 -->
    <div>
        <el-row style="margin-bottom: 10px;">
            <div class="flex">
                <el-tag v-for="tag in searchTags" :key="tag" closable :color="stringToColor(tag)"
                        @close="closeSearchTag(tag)">
                    {{ tag }}
                </el-tag>
                <el-input
                    v-if="searchTagInputVisible"
                    ref="searchTagInputRef"
                    v-model="searchTagInputValue"
                    class="w-20"
                    size="small"
                    @keyup.enter="searchTagInputConfirm"
                    @blur="searchTagInputConfirm"
                />
                <el-button v-else @click="showSearchTagInput">
                    + 搜索标签
                </el-button>
                <el-button v-show="searchTags.length>0" @click="clearSearchTag">
                    清空标签
                </el-button>
            </div>
            <div style="flex-grow: 1;"></div>
            <el-col :span="3">
                <el-button @click="addQuickJump" type="primary" plain
                           v-if="checkPermission('quickJump:add')">添加快速跳转
                </el-button>
            </el-col>
        </el-row>
        <el-table :data="tableData" border v-loading="tableLoading">
            <el-table-column prop="name" label="名称" width="200px"/>
            <el-table-column prop="url" label="URL" width="300px">
                <template #default="data">
                    <el-button type="primary" link @click="jump(data.row.url)">{{ data.row.url }}</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="tagList" label="标签">
                <template #default="data">
                    <el-tag v-for="tag in data.row.tagList" :color="stringToColor(tag)"
                            @click="addSearchTag(tag)">
                        {{ tag }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" v-if="checkPermission('quickJump:edit')">
                <template #default="data">
                    <el-button type="info" plain size="small" :disable="!quickJumpDialogVisible"
                               @click="editQuickJump(data.row)" v-if="checkPermission('quickJump:edit')">
                        编辑
                    </el-button>
                    <el-button type="danger" plain size="small" :disable="!quickJumpDialogVisible"
                               @click="removeQuickJump(data.row)" v-if="checkPermission('quickJump:remove')">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 快速跳转编辑对话框 -->
        <el-dialog v-model="quickJumpDialogVisible" :title="quickJumpDialogTitle" width="400px" draggable>
            <template #default>
                <el-form v-if="quickJumpDialogForm" :model="quickJumpDialogForm" v-loading="quickJumpDialogFormLoading"
                         label-width="auto" ref="quickJumpDialogFormRef" :rules="quickJumpDialogFormFormRules">
                    <el-form-item label="名称" prop="name">
                        <el-input v-model="quickJumpDialogForm.name">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="URL" prop="url">
                        <el-input v-model="quickJumpDialogForm.url">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="标签" prop="tags">
                        <div>
                            <el-tag v-for="tag in quickJumpDialogForm.tagList" :key="tag" closable
                                    :color="stringToColor(tag)" @close="closeDialogTag(tag)">
                                {{ tag }}
                            </el-tag>
                            <el-input
                                v-if="quickJumpDialogTagInputVisible"
                                ref="quickJumpDialogTagInputRef"
                                v-model="quickJumpDialogTagInputValue"
                                class="w-20"
                                size="small"
                                @keyup.enter="quickJumpDialogTagInputConfirm"
                                @blur="quickJumpDialogTagInputConfirm"
                            />
                            <el-button v-else @click="showDialogTagInput">
                                + 标签
                            </el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <el-button @click="quickJumpDialogVisible = false"
                           :loading="quickJumpDialogFormSubmitLoading">关闭
                </el-button>
                <el-button @click="quickJumpDialogFormReset">重置</el-button>
                <el-button type="primary" @click="quickJumpDialogFormSubmit">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {ref, onMounted, nextTick} from 'vue'
import {ElMessage, FormRules, FormInstance, ElMessageBox, ElInput} from 'element-plus';
import {myAxios} from '../assets/ts/my-axios'
import {checkPermission} from '../assets/ts/permission-util'
import {stringToColor} from "../assets/ts/common-util.ts";

// 数据
const tableData = ref<Array<QuickJumpInfo>>([])

// 点击打开页面
function jump(url: string) {
    window.open(url)
}

// 生命周期 - 挂载
onMounted(() => {
    loadQuickJump()
})

// ====================================== 定义 ===========================================

interface QuickJumpInfo {
    id: number
    name: string
    url: string
    tagList: Array<string>
}

// ====================================== 表格 ===========================================

// 表格加载遮罩
const tableLoading = ref(false)

// 加载表格数据
function loadQuickJump() {
    tableLoading.value = true
    let params = {searchTags: searchTags.value + ''}
    myAxios.get('/quick-jump/list', {params: params})
        .then((response: any) => {
            if (response.data.code == 0) {
                tableData.value = response.data.data
            } else {
                ElMessage.error(response.data.message)
            }
        }).finally(() => {
        tableLoading.value = false
    })
}

// ====================================== 搜索栏标签 ===========================================

const searchTags = ref<Array<string>>([])
const searchTagInputVisible = ref(false)
const searchTagInputValue = ref('')
const searchTagInputRef = ref<InstanceType<typeof ElInput>>()

// 展示标签输入
function showSearchTagInput() {
    searchTagInputVisible.value = true
    nextTick(() => {
        searchTagInputRef.value!.input!.focus()
    })
}

// 提交标签输入
function searchTagInputConfirm() {
    if (searchTagInputValue.value) {
        addSearchTag(searchTagInputValue.value)
    }
    searchTagInputVisible.value = false
    searchTagInputValue.value = ''
}

// 添加标签
function addSearchTag(tag: string) {
    if (searchTags.value.indexOf(tag) < 0) {
        searchTags.value.push(tag)
        // 触发加载
        loadQuickJump()
    }
}

// 删除标签
function closeSearchTag(tag: string) {
    searchTags.value.splice(searchTags.value.indexOf(tag), 1)
    // 触发加载
    loadQuickJump()
}

// 清空标签
function clearSearchTag() {
    searchTags.value = []
    // 触发加载
    loadQuickJump()
}


// ====================================== 对话框 ===========================================

enum QuickJumpDialogType { add, edit }

const quickJumpDialogVisible = ref(false)
const quickJumpDialogTitle = ref('')
const quickJumpDialogType = ref(QuickJumpDialogType.add)
const quickJumpDialogForm = ref<QuickJumpInfo>()
const quickJumpDialogFormRef = ref<FormInstance>()
const quickJumpDialogFormLoading = ref(false)
const quickJumpDialogFormSubmitLoading = ref(false)
let quickJumpDialogFormSource: QuickJumpInfo

// 编辑
function editQuickJump(quickJumpInfo: QuickJumpInfo) {
    // 类型为编辑
    quickJumpDialogType.value = QuickJumpDialogType.edit
    quickJumpDialogTitle.value = '编辑快速跳转'
    // 表单初始化
    quickJumpDialogFormSource = {...quickJumpInfo}
    quickJumpDialogFormReset()
    // 展示面板
    quickJumpDialogVisible.value = true
}

// 添加
function addQuickJump() {
    // 类型为添加
    quickJumpDialogType.value = QuickJumpDialogType.add
    quickJumpDialogTitle.value = '添加快速跳转'
    // 表单初始化
    quickJumpDialogFormSource = {id: 0, name: '', url: '', tagList: []}
    quickJumpDialogFormReset()
    // 展示面板
    quickJumpDialogVisible.value = true
}

// 表单重置
function quickJumpDialogFormReset() {
    quickJumpDialogForm.value = {...quickJumpDialogFormSource}
    quickJumpDialogFormRef.value?.clearValidate()
    quickJumpDialogTagInputVisible.value = false
    quickJumpDialogTagInputValue.value = ''
    !quickJumpDialogForm.value.tagList ? quickJumpDialogForm.value.tagList = [] : 1
}

// 表单验证规则
const quickJumpDialogFormFormRules = ref<FormRules>({
    name: [
        {required: true, message: "请输入名称", trigger: "blur"},
    ],
    url: [
        {required: true, message: "请输入URL", trigger: "blur"},
    ],
})

// 表单提交
function quickJumpDialogFormSubmit() {
    quickJumpDialogFormRef.value?.validate((valid, _fields) => {
        if (valid) {
            let apiUrl =
                quickJumpDialogType.value == QuickJumpDialogType.add ? '/quick-jump/add'
                    : quickJumpDialogType.value == QuickJumpDialogType.edit ? '/quick-jump/edit'
                        : ''
            quickJumpDialogFormSubmitLoading.value = true
            myAxios.post(apiUrl, quickJumpDialogForm.value)
                .then((response: any) => {
                    if (response.data.code == 0) {
                        ElMessage.success("保存成功")
                        loadQuickJump()
                        quickJumpDialogVisible.value = false
                    } else {
                        ElMessage.error(response.data.message)
                    }
                })
                .finally(() => {
                    quickJumpDialogFormSubmitLoading.value = false
                })
        }
    })
}

// ====================================== 对话框标签 ===========================================

const quickJumpDialogTagInputVisible = ref(false)
const quickJumpDialogTagInputValue = ref('')
const quickJumpDialogTagInputRef = ref<InstanceType<typeof ElInput>>()

// 展示标签输入
function showDialogTagInput() {
    quickJumpDialogTagInputVisible.value = true
    nextTick(() => {
        quickJumpDialogTagInputRef.value!.input!.focus()
    })
}

// 提交标签输入
function quickJumpDialogTagInputConfirm() {
    if (quickJumpDialogTagInputValue.value) {
        addDialogTag(quickJumpDialogTagInputValue.value)
    }
    quickJumpDialogTagInputVisible.value = false
    quickJumpDialogTagInputValue.value = ''
}

// 添加标签
function addDialogTag(tag: string) {
    if (quickJumpDialogForm.value) {
        if (quickJumpDialogForm.value.tagList.indexOf(tag) < 0) {
            quickJumpDialogForm.value.tagList.push(tag)
        }
    }
}

// 删除标签
function closeDialogTag(tag: string) {
    if (quickJumpDialogForm.value) {
        quickJumpDialogForm.value.tagList.splice(quickJumpDialogForm.value.tagList.indexOf(tag), 1)
    }
}


// ====================================== 表格操作 ===========================================

// 删除
function removeQuickJump(quickJumpInfo: QuickJumpInfo) {
    ElMessageBox.confirm(
        '是否确认删除快速跳转:' + quickJumpInfo.name,
        '删除',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 删除权限
        myAxios.post('/quick-jump/remove', {id: quickJumpInfo.id})
            .then((response) => {
                    if (response.data.code == 0) {
                        ElMessage.success("删除成功")
                        loadQuickJump()
                    } else {
                        ElMessage.error(response.data.message)
                    }
                }
            )
    }).catch((e: any) => {
        console.log("取消 e:" + e)
    })
}

// ====================================== 工具 ===========================================

// 字符串颜色
// function stringToColor(str: string) {
//     let hash = 0;
//     for (let i = 0; i < str.length; i++) {
//         hash = str.charCodeAt(i) + ((hash << 5) - hash);
//     }
//
//     let color = '#';
//     for (let i = 0; i < 3; i++) {
//         let value = (hash >> (i * 8)) & 0xFF;
//         color += ('00' + value.toString(16)).substr(-2);
//     }
//     return color;
// }

</script>

<style scoped>

.el-tag {
    margin: 5px;
}

</style>